package com.hcr.elecident;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hcr.entity.WxResult;
import com.hcr.util.MyConst;
import com.hcr.util.WXPayUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class PayActivity extends Activity {
	
	public static final String DYNAMICACTION = "com.hcr.elecident.wxpay"; // 动态广播的Action字符串

	private IntentFilter dynamic_filter;
	private IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	private WXPayUtils wxpayUtils;
	
	private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(DYNAMICACTION)) { // 动作检测
				int msg = intent.getIntExtra("wechatResult", 0);
				if (msg == 0) {
					Toast.makeText(context, "支付成功", Toast.LENGTH_LONG).show();
//					finish();
				} else {
					Toast.makeText(context, "支付失败", Toast.LENGTH_LONG).show();
//					finish();
				}
			}
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		OkHttpClient client = new OkHttpClient();
		RequestBody body = new FormBody.Builder()
				.add("hid", "1")
				.add("totalFee", "1")
				.add("uid", "1")
				.build();

		Request request = null;
		try {
			request = new Request.Builder()
					.url(new URL(MyConst.HT+ "weixin/order"))
					.post(body)
					.build();

			Response response = null;
			try {
				response = client.newCall(request).execute();
			} catch (IOException e) {
				e.printStackTrace();
			}
			String responseData = null;
			try {
				responseData = response.body().string();
			} catch (IOException e) {
				e.printStackTrace();
			}

			WxResult result = JSON.parseObject(responseData, new  WxResult().getClass());
//			System.out.println(result);

			if (!"".equals(result.getPrepayid()) || null != result.getPrepayid()){
				PayReq req = new PayReq();
				req.appId = result.getAppid();
				req.partnerId = result.getPartnerid();
				req.prepayId = result.getPrepayid();
				req.packageValue = "Sign=WXPay";
				req.nonceStr = result.getNoncestr();
				req.timeStamp = result.getTimestamp();

				wxpayUtils = new WXPayUtils(this);
				msgApi.registerApp(MyConst.APP_ID);

				wxpayUtils.genPayReq(req);
//            {nonce_str=EnMdHis9Cn6xAHl9, appid=wx9663c70fe35ebdc4,
//                    sign=2BEB9974C8B2B7778EA00A07B2EABEA2, trade_type=APP, return_msg=OK,
//                    result_code=SUCCESS,
//                    mch_id=1549669361, return_code=SUCCESS, prepay_id=wx0920194391985782267082411138175300}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}


		super.onCreate(savedInstanceState);

	}
	
	@Override
	protected void onStart() {
		super.onStart();
		dynamic_filter = new IntentFilter();
		dynamic_filter.addAction(DYNAMICACTION); // 添加动态广播的Action
		registerReceiver(dynamicReceiver, dynamic_filter); // 注册自定义动态广播消息
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(dynamicReceiver);
	}
}